#!/bin/bash
set -e

# 检查参数
if [ $# -ne 1 ]; then
  echo "Usage: sudo $0 <hostname>"
  exit 1
fi
NEW_HOSTNAME=$1
ip=$(hostname -I | awk '{print $1}');
# 设置主机名
hostnamectl set-hostname $NEW_HOSTNAME
echo "$ip $NEW_HOSTNAME" >> /etc/hosts

# 关闭 Swap
swapoff -a
sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

# 加载内核模块
cat <<EOF | tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF
modprobe br_netfilter

# 设置系统参数
cat <<EOF | tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
sysctl --system

# 安装依赖工具
if [ -x "$(command -v yum)" ]; then
  yum install -y yum-utils device-mapper-persistent-data lvm2 curl
  # 设置阿里云基础镜像源
  mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
  curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
  yum clean all && yum makecache
fi

# 安装 Docker（阿里云镜像源）
if [ -x "$(command -v yum)" ]; then
  # 添加阿里云Docker仓库
  yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
  yum install -y docker-ce docker-ce-cli containerd.io
fi

# 启动 Docker
systemctl enable --now docker

# 配置 Docker（阿里云镜像加速）
mkdir -p /etc/docker
cat <<EOF | tee /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "registry-mirrors": ["https://z3zetxph.mirror.aliyuncs.com"]
}
EOF
systemctl restart docker

# 安装 Kubernetes（阿里云镜像源）
if [ -x "$(command -v yum)" ]; then
  cat <<EOF | tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
  yum install -y kubelet kubeadm kubectl
fi

# 启动 kubelet
systemctl enable --now kubelet

echo "Common setup completed on $NEW_HOSTNAME! (Using Aliyun Mirrors)"